# from rest_framework_jwt.views import jwt_response_payload_handler
# from rest_framework_jwt.utils import jwt_response_payload_handler # 源码中的返回值如果不重写就是使用这个,只会返回token
from django.contrib.auth.backends import ModelBackend
from users.models import User
import re

def jwt_response_payload_handler(token, user=None, request=None):

    return {
        'token':token,
        'username':user.username,
        'user_id':user.id
    }

class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            if re.match(r'1[3-9]\d{9}',username):
                user = User.objects.get(mobile=username)
            elif re.match(r'\w+@\w+.\w+',username):
                user = User.objects.get(email=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None
        else:
            if user is not None and user.check_password(password):
                return user
